package com.hx.demo.handle;

import com.alibaba.fastjson.JSONObject;
import com.hx.demo.util.AjaxResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        AjaxResult ajaxResult = AjaxResult.error(e.getMessage());
        printWriter.append(JSONObject.toJSONString(ajaxResult));
        printWriter.close();


//        response.setContentType("application/json;charset=UTF-8");
//        response.setStatus(401);
//        PrintWriter out = response.getWriter();
//        out.write("{\n" +
//                "    \"error_code\": 401,\n" +
//                "    \"error_name\":" + "\"" + e.getClass().getName() + "\",\n" +
//                "    \"message\": \"请求失败," + e.getMessage() + "\"\n" +
//                "}");
    }

}
